import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_yres/model/vip_shoplist_model.dart';
import 'package:flutter_yres/pages/user/vip_order/BuyGoods.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_yres/pages/user/vip_order/OrderPay.dart';
import 'package:cached_network_image/cached_network_image.dart';

class VipShopDetailPage extends StatefulWidget {
  VipShopListModelData vipmodel;
  VipShopDetailPage({Key key, this.vipmodel}) : super(key: key);

  @override
  _VipShopDetailPageState createState() => _VipShopDetailPageState(vipmodel);
}

class _VipShopDetailPageState extends State<VipShopDetailPage> {
  VipShopListModelData vipmodel;
  _VipShopDetailPageState(this.vipmodel);

  String goods_name = ''; //商品名称
  String price = '';
  String content = ''; //详情
  Map goods_details = new Map();
  String sku = '未选择';
  List skuList = [];

  List bannerData = []; //轮播图数组
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text('商品详情',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: goods_name == ''
          ? Container()
          : Stack(children: <Widget>[
              Container(
                  // height: kScreenHeight +
                  //     kWindowstateHeight +
                  //     56,
                  child: SingleChildScrollView(
                      child: Column(children: <Widget>[
                _buildBanner(),
                Container(
                    color: white,
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setWidth(15),
                        0,
                        ScreenUtil.getInstance().setWidth(15),
                        ScreenUtil.getInstance().setWidth(15)),
                    child: Text(
                      goods_name,
                      style: TextStyle(fontSize: 17),
                    )),
                Container(
                  color: white,
                  padding:
                      EdgeInsets.all(ScreenUtil.getInstance().setWidth(15)),
                  child: Row(
                    children: <Widget>[
                      // Expanded(
                      // child:
                      RichText(
                        textAlign: TextAlign.left,
                        text: TextSpan(
                            style: TextStyle(color: Colors.red),
                            children: [
                              TextSpan(
                                  text: '¥', style: TextStyle(fontSize: 18.0)),
                              TextSpan(
                                  text: price,
                                  style: TextStyle(fontSize: 20.0)),
                            ]),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      )
                    ],
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    if (skuList.length > 0) {
                      print('有属性');
                      showDialog<Null>(
                        context: context,
                        builder: (BuildContext context) {
                          return new SimpleDialog(
                            title: new Text('选择商品规格'),
                            children: <Widget>[buildGrid()],
                          );
                        },
                      ).then((val) {
                        print(val);
                      });
                    } else {
                      print('无属性');
                    }
                  },
                  child: Container(
                    color: white,
                    padding:
                        EdgeInsets.all(ScreenUtil.getInstance().setWidth(15)),
                    alignment: Alignment.centerLeft,
                    child: Text('规格选择:' + sku),
                  ),
                ),
                Container(
                  margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(20)),
                  child: Text('商品详情'),
                ),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                  child: Html(data: content),
                )
              ]))),
            ]),
      bottomNavigationBar: BottomAppBar(
          child: Row(
        children: <Widget>[
          Expanded(
              // flex: 2,
              child: RaisedButton(
            child: Text(
              '立即购买',
              style: TextStyle(color: Colors.white),
            ),
            // icon: Icon(Icons.share),
            color: Colors.red,
            onPressed: () {
              if (skuList.length > 0 && sku == '未选择') {
                print('有属性');
                showDialog<Null>(
                  context: context,
                  builder: (BuildContext context) {
                    return new SimpleDialog(
                      title: new Text('选择商品规格'),
                      children: <Widget>[buildGrid()],
                    );
                  },
                ).then((val) {
                  print(val);
                });
                return;
              } else {
                print('无属性');
              }
              _order(this.vipmodel.goods_id.toString());
            },
          )),
          // Expanded(
          //     flex: 3,
          //     child: RaisedButton.icon(
          //       label: Text('领券'),
          //       icon: Icon(Icons.share),
          //       color: Colors.red,
          //       onPressed: () {},
          //     ))
        ],
      )),
    );
  }

  Widget buildGrid() {
    List<Widget> tiles = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in skuList) {
      tiles.add(
        new SimpleDialogOption(
          child: new Text(item),
          onPressed: () {
            Navigator.of(context).pop();
            print(item);
            setState(() {
              sku = item;
            });
          },
        ),
      );
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

//轮播图组件
  _buildBanner() {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750),
      child: Swiper(
        itemBuilder: _swiperBuilder,
        itemCount: bannerData.length,
        loop: false,
        autoplay: true,
        autoplayDelay: 15000,
        pagination: new SwiperPagination(
            builder: DotSwiperPaginationBuilder(
          color: Colors.black54,
          activeColor: Colors.white,
        )),
        scrollDirection: Axis.horizontal,
        onTap: (index) {
          //点击轮播图事件
        },
      ),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return (CachedNetworkImage(
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750),
      fit: BoxFit.fill,
      imageUrl: Api.BaseUrl + bannerData[index]['img'],
      placeholder: (context, url) => Image.asset('images/pic_default.png',
          fit: BoxFit.fill,
          width: ScreenUtil.getInstance().setWidth(750),
          height: ScreenUtil.getInstance().setWidth(750)),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setWidth(750),
        height: ScreenUtil.getInstance().setWidth(750),
        fit: BoxFit.fill,
      ),
    ));
  }

  @override
  void initState() {
    _getLoginMsg();
    super.initState();
  }

  void _getLoginMsg() async {
    // SharedPreferences preferences = await SharedPreferences.getInstance();
    // var token = preferences.get("token");
    // print(token);
    // print(this.vipmodel.goods_id);
    // if (token == null || token == '') {
    //   //未登陆
    //   Navigator.of(context).pushNamed("login");
    // } else {
    _getDetailUrl(this.vipmodel.goods_id.toString());
    // }
  }

  _order(String goods_id) async {
    //下单
    SharedPreferences preferences = await SharedPreferences.getInstance();
    var token = preferences.get("token");
    if (token == null || token == '') {
      Navigator.of(context).pushNamed("login");
    } else {
      if (goods_details['is_send'] == 'N') {
        Map map = new Map();
        map['token'] = token;
        map['goods_id'] = goods_id;
        if (skuList.length > 0) {
          map['sku'] = sku;
        }
        // else{
        //   map['sku'] = '';
        // }
        print(map);
        FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
        Response<String> response =
            await HttpUtil().post(Api.VipShopOrderUrl, data: data);
        Map userMap = json.decode(response.data);
        print('立即购买');
        print(userMap);
        if (userMap['code'] == 1) {
          if (mounted) {
            Fluttertoast.showToast(msg: '下单成功');
            Navigator.of(context).pop("1");
            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
              return new OrderPayPage(
                  orderId: userMap['data']['order_id'],
                  title: userMap['data']['title'],
                  orderNum: userMap['data']['order_num'],
                  totalMoney: userMap['data']['pay_price'].toString());
            }));
          }
        }
      } else {
        String skuJson = '';
        if (skuList.length > 0) {
          skuJson = sku;
        }
        Navigator.of(context)
            .push<String>(MaterialPageRoute(builder: (context) {
          return BuyGoodsPage(
            old: goods_details['old_price'],
            goods_id: this.vipmodel.goods_id,
            type: 'vip',
            goods_name: goods_name,
            goods_num: '1',
            goods_img: goods_details['img'],
            price: price.toString(),
            skuJson: skuJson,
            id: '0',
            skuInfo: "无配置",
          );
        }));
      }
    }
  }

//商品详情
  _getDetailUrl(String goods_id) async {
    FormData data = new FormData.fromMap({'goods_id': goods_id});
    Response<String> response =
        await HttpUtil().post(Api.VipShopMsgUrl, data: data);
    Map userMap = json.decode(response.data);

    if (userMap['code'] == 1) {
      if (mounted) {
        goods_details = userMap['data']['goodsMsg'];
        print(goods_details);
        Map catMsg = userMap['data']['catMsg'];
        setState(() {
          bannerData = userMap['data']['imglist'];
          goods_name = goods_details['goods_name'];
          // sku = goods_details['sku'];
           print('商品属性');
          if (goods_details['sku'] ==''||(goods_details['sku'] == null || goods_details['sku'] == 'null')) {
          skuList=[];
          } else {
            skuList = goods_details['sku'].split('-');
          }
          print(skuList.length);

          price = goods_details['price'];
          if (goods_details['content'] == '' ||
              goods_details['content'] == null) {
            content = '<p></p>';
          } else {
            content = goods_details['content'];
          }

          print(price);
        });
      }
    }
  }
}
